package com.conversationboard.error;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.Principal;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;

@WebServlet(name = "ErrorServlet", urlPatterns = "/ErrorServlet")
public class ErrorServlet extends HttpServlet {

	private static final long serialVersionUID = -4072764568497143399L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/errorpage.jsp");
			request.setAttribute("message", "An error has occurred; please try again shortly.");

			Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");

			if (!(throwable instanceof NumberFormatException)) {
				StringWriter writer = new StringWriter();
				PrintWriter printWriter = new PrintWriter(writer, true);
				throwable.printStackTrace(printWriter);
				printWriter.flush();
				writer.flush();

				Principal principal = request.getUserPrincipal();
				User user = User.getAnonymousUser();

				if (principal != null) {
					user = User.get(principal.getName());
				}

				Logger.log(new Date(), writer.toString(), user);
			}

			dispatcher.forward(request, response);

		} catch (Throwable t) {

			/*
			 * Must ensure this method doesn't throw an exception or we'll
			 * recurse
			 */

			System.out.println("\n\n\n\n\n\n\n\n\n\n\n  ******* Error in ErrorServlet class. \n\n\n");
			t.printStackTrace();

		}
	}

}
